﻿using MediatR;
using PublicClass;
using S.RBAC.Domain.Dto;
using S.RBAC.Infrastructure.Interface;
using S.RBAC.Read.Api.Application.Command.RoleJurisdictionCommand;

namespace S.RBAC.Read.Api.Application.CommandHandlers.RoleJurisdictionHandler
{
    public class RoleJurisdictionGetAllCommandHandler : IRequestHandler<RoleJurisdictionGetAllCommand, PageInfo<RoleJurisdictionDto>>
    {
        protected readonly IRoleJurisdictionRepository _roleJurisdiction;
        protected readonly IRoleRepository _role;
        protected readonly IJurisdictionRepository _jurisdiction;
        protected readonly IOperationRepository _operation;

        public RoleJurisdictionGetAllCommandHandler(IRoleJurisdictionRepository roleJurisdiction, IRoleRepository role, IJurisdictionRepository jurisdiction, IOperationRepository operation)
        {
            _roleJurisdiction = roleJurisdiction;
            _role = role;
            _jurisdiction = jurisdiction;
            _operation = operation;
        }

        public async Task<PageInfo<RoleJurisdictionDto>> Handle(RoleJurisdictionGetAllCommand request, CancellationToken cancellationToken)
        {
            //var list = await _roleJurisdiction.GetAllRoleJurisdiction();

            //foreach(var item in list)
            //{
            //    var ids = item.OperationIds.Split(",");

            //    foreach(var id in ids)
            //    {
            //        var operationInfo = _operation.GetOperation((int)id);
            //    }
            //}

            var info = (from a in await _roleJurisdiction.GetAllRoleJurisdiction()
                        join b in await _role.GetAllRole() on a.RoleId equals b.RoleId
                        join c in await _jurisdiction.GetAllJurisdiction() on a.JurisdictionId equals c.JurisdictionId
                        where a.IsDel == false
                        select new RoleJurisdictionDto
                        {
                            RJId = a.RJId,
                            OperationIds = a.OperationIds,
                            RoleId = b.RoleId,
                            RoleName = b.RoleName,
                            JurisdictionId = c.JurisdictionId,
                            JurisdictionName = c.JurisdictionName
                        }).ToList();

            //总行数
            int totalCount = info.Count;
            //总页数
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            //分页
            info = info.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            return new PageInfo<RoleJurisdictionDto> { pageCount = pageCount, totalCount = totalCount, datas = info };
        }
    }
}
